import { 
  AmbientLight,
  BufferGeometry,
  Color,
  Geometry,
  Line,
  LineBasicMaterial,
  PerspectiveCamera, Scene, ShaderMaterial, sRGBEncoding, Vector3, WebGLRenderer 
} from "three"
import { TrackballControls } from 'three/examples/jsm/controls/TrackballControls'

const scene = new Scene();
const camera = new PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000);
camera.position.set(10, 0, 10);
camera.lookAt(0, 0, 0);

const vertexShader = `
  varying vec3 vPos;
  void main() {
    vPos = position;
    vec4 modelViewPosition = modelViewMatrix * vec4(position, 1.0);
    gl_Position = projectionMatrix * modelViewPosition;
  }
`
const fragmentShader = `
  uniform vec3 origin;
  uniform vec3 color;
  uniform float limitDistance;
  varying vec3 vPos;

  void main() {
    float distance = clamp(length(vPos - origin), 0., limitDistance);
    float opacity = 1. - distance / limitDistance;
    gl_FragColor = vec4(color, opacity);
  }
`
const lineGeom = new BufferGeometry().setFromPoints([
  new Vector3(0, 0, 0),
  new Vector3(1, -3, 1)
]);
lineGeom.attributes.position.needsUpdate = true;
const lineShader = new ShaderMaterial({
  uniforms: {
    color: { value: new Color(0x00ff00) },
    origin: { value: new Vector3(0,0,0) },
    limitDistance: { value: 1.0 }
  },
  vertexShader,
  fragmentShader,
  transparent: true
})
const line = new Line(lineGeom, lineShader);
scene.add(line);

scene.add(new AmbientLight(0xffffff));

const renderer = new WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);

document.body.appendChild(renderer.domElement);
const trackballControls = new TrackballControls(camera, renderer.domElement);

function render() {
  trackballControls.update()

  requestAnimationFrame(render)
  renderer.render(scene, camera)
}

render();